using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace QLThuChi.Repositories
{
	#region using
	using QLThuChi.Models;
	#endregion
	public class NhanCongRepository
	{
		public static List<NhanCong> SelectAll()
		{
			return DataContext.Instance.NhanCongs.OrderBy(item => item.TenNhanCong).ToList();
		}

		public static NhanCong SelectByID(int manhancong)
		{
			return DataContext.Instance.NhanCongs.FirstOrDefault(item => item.MaNhanCong == manhancong );
		}

		public static bool Insert(NhanCong obj)
		{
			try
			{
				DataContext.Instance.NhanCongs.AddObject(obj);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Delete(int manhancong)
		{
			try
			{
				var delitem = DataContext.Instance.NhanCongs.FirstOrDefault(item => item.MaNhanCong == manhancong );
				DataContext.Instance.NhanCongs.DeleteObject(delitem);
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

		public static List<NhanCong> RetrieveByID(int manhancong)
		{
			return (from item in DataContext.Instance.NhanCongs where  item.MaNhanCong == manhancong  select item).ToList();
		}

		public static List<NhanCong> SelectByMaBophan(int mabophan)
		{
			var lstItem = (from item in DataContext.Instance.NhanCongs where item.MaBophan == mabophan select item).ToList();
			return lstItem;
		}

		public static List<NhanCong> SelectByMaLoaiNhanCong(int maloainhancong)
		{
			var lstItem = (from item in DataContext.Instance.NhanCongs where item.MaLoaiNhanCong == maloainhancong select item).ToList();
			return lstItem;
		}

        public static List<NhanCong> Search(string id, string name)
        {
            var lst = new List<NhanCong>();
            foreach (var item in DataContext.Instance.NhanCongs)
            {
                if (item.MaNhanCong == (id == "" ? item.MaNhanCong : int.Parse(id)) &&
                        item.TenNhanCong.ToUpper().Contains(name == "" ? item.TenNhanCong.ToUpper() : name.Trim().ToUpper()))
                {
                    lst.Add(item);
                }
            }
            return lst;
        }
	}
}